package za.ac.wits.was.user.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;
import za.ac.wits.was.user.model.Authority;
import za.ac.wits.was.user.model.User;

/**
 *
 * @author Salman Noor : School of Electrical and Information Engineering
 * @Copyright: Wits University 2013 - All Rights Reserved
 * @email: salmannoor74415@gmail.com
 * @License: BSD License (http://www.linfo.org/bsdlicense.html)
 */
@Service
public class WASAutheticator implements AuthenticationProvider {

    Logger L = Logger.getLogger(WASAutheticator.class);
    @Autowired
    UserService userService;

    @Override
    public Authentication authenticate(Authentication a) throws AuthenticationException {
        List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();
        User systemUser = this.userService.authenticateUser(a.getName(), a.getCredentials().toString());
        if (systemUser != null) {
            AUTHORITIES.clear();
            Set<Authority> userAuthorities = systemUser.getUser_authorities();
            for (Authority auth : userAuthorities) {
                AUTHORITIES.add(new SimpleGrantedAuthority(auth.getAuthority()));
            }
            return new UsernamePasswordAuthenticationToken(a.getName(), a.getCredentials(), AUTHORITIES);
        }
        
        throw new BadCredentialsException("Login failed with username " + a.getName());
        
    }

    @Override
    public boolean supports(Class<? extends Object> authentication) {
        return true;
    }
    
    
}
